find_path(MBEDTLS_INCLUDE_DIR mbedtls/ssl.h)

find_library(MBEDTLS_LIBRARY mbedtls)
find_library(MBEDX509_LIBRARY mbedx509)
find_library(MBEDCRYPTO_LIBRARY mbedcrypto)

if(MBEDTLS_INCLUDE_DIR)
  file(STRINGS "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h"
      MBEDTLS_VERSION_MAJOR REGEX "^#define[ \t]+MBEDTLS_VERSION_MAJOR[ \t]+[0-9]+")
  file(STRINGS "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h"
      MBEDTLS_VERSION_MINOR REGEX "^#define[ \t]+MBEDTLS_VERSION_MINOR[ \t]+[0-9]+")
  file(STRINGS "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h"
      MBEDTLS_VERSION_PATCH REGEX "^#define[ \t]+MBEDTLS_VERSION_PATCH[ \t]+[0-9]+")
  string(REGEX REPLACE "[^0-9]+" "" MBEDTLS_VERSION_MAJOR "${MBEDTLS_VERSION_MAJOR}")
  string(REGEX REPLACE "[^0-9]+" "" MBEDTLS_VERSION_MINOR "${MBEDTLS_VERSION_MINOR}")
  string(REGEX REPLACE "[^0-9]+" "" MBEDTLS_VERSION_PATCH "${MBEDTLS_VERSION_PATCH}")
  set(MBEDTLS_VERSION "${MBEDTLS_VERSION_MAJOR}.${MBEDTLS_VERSION_MINOR}.${MBEDTLS_VERSION_PATCH}")
  unset(MBEDTLS_VERSION_MINOR)
  unset(MBEDTLS_VERSION_MAJOR)
  unset(MBEDTLS_VERSION_PATCH)
endif()

set(MBEDTLS_LIBRARIES "${MBEDTLS_LIBRARY}" "${MBEDX509_LIBRARY}" "${MBEDCRYPTO_LIBRARY}")

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(MbedTLS
    REQUIRED_VARS
        MBEDTLS_LIBRARY
        MBEDX509_LIBRARY
        MBEDCRYPTO_LIBRARY
        MBEDTLS_INCLUDE_DIR
    VERSION_VAR
    	MBEDTLS_VERSION
)

mark_as_advanced(MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY)